const multer=require('multer');
const path=require('path');
const os = require("os")
// let obj=os.networkInterfaces();
// let address=''
// for(var i in obj){
//     if(i==='以太网'){
//         address=obj[i].find(item=>item.family==='IPv4').address
//     }
// }
// console.log(address,'address')
///获取本机ip///
function getIPAdress() {
    var interfaces = os.networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}
const myHost = getIPAdress();
console.log(myHost)
const uploadAvatar=(req,res,next)=>{
     //定制磁盘存储
     const storage=multer.diskStorage({
         destination(req,file,cb){//设置文件存储路径
            const filepath=path.resolve('./assets','avatar')//这2个文件夹需提前存在，
            cb(null,filepath)
         },
         filename(req,file,cb){//设置文件的名字
            let filename=+new Date()+'';
            //使用正则处理后缀名
            let reg=/\.[^\.]+$/
            let extName=reg.exec(file.originalname);
            filename=filename+extName[0];
            //给body添加一个属性，保存的就是头像图片的路径
            // req.body.avatarUrl='http://127.0.0.1:3000/avatar/'+filename
            req.body.avatarUrl='/avatar/'+filename
            cb(null,filename);
         }
     })
     //再次调用multer,将storage传入
     const uploads=multer({storage}).single('avatar')

     //错误处理
     uploads(req,res,function(err){
         if(err){
             res.send({httpStatus:400,msg:'文件上传出错',err})
         }else{
             next()
         }
     })
}
module.exports=uploadAvatar